from datetime import date, timedelta
from rest_framework.response import Response
from rest_framework.permissions import IsAdminUser
from rest_framework.views import APIView

from users.models import User


#用户总计
from goods.models import GoodsVisitCount


class UserCountView(APIView):
    # 指定权限
    permission_classes = [IsAdminUser]
    def get(self,request):
        count = User.objects.filter(is_staff=False).count()
        return Response({
            'count':count
        })

# 用户日增
class UserAddView(APIView):
    permission_classes = [IsAdminUser]
    def get(self,request):
        now_date = date.today()
        count = User.objects.filter(is_staff = False,date_joined__gte=now_date).count()
        return Response({
            'count':count,
            'date':now_date
        })

# 日活跃
class UserDayActiveView(APIView):
    permission_classes = [IsAdminUser]
    def get(self, request):
        now_date = date.today()
        count = User.objects.filter(is_staff = False,last_login__gte=now_date).count()
        return Response({
            'count': count,
            'date': now_date
        })

# 日下单
class UserOrderView(APIView):
  permission_classes = [IsAdminUser]
  def get(self,request):
      now_date = date.today()
      users = set(User.objects.filter(is_staff = False,orders__create_time__gte=now_date))
      count = len(users)
      return Response({
          'count':count
      })

# 月增

class UserMonthView(APIView):
    permission_classes = [IsAdminUser]
    def get(self,request):
        now_date = date.today()
        start_date = now_date - timedelta(30)
        data_list = []
        for i in range(31):
            index_date = start_date + timedelta(i)
            next_date = start_date + timedelta(i+1)
            count = User.objects.filter(is_staff=False, date_joined__gte=index_date, date_joined__lt=next_date).count()
            data_list.append({
                'count':count,
                'date':index_date
            })
        return Response(data_list)

# 日访问
class GoodsTypeView(APIView):
    permission_classes = [IsAdminUser]
    def get(self,request):
        now_date = date.today()
        goods = GoodsVisitCount.objects.filter(date__gte=now_date)
        data_list =[]
        for good in goods:
            data_list.append({
                'count':good.count,
                'category':good.category.name,
            })
            return Response(data_list)